// Shared dimensions:
var tile_width = 32;
var tile_height = 32;
var map_width = 16;
var map_height = 16;

// Mouse hover location:
var hover_x = -1;
var hover_y = -1;

// Tile definitions:
var tiles = {
  ' ' : { bg : 'floor', passable : true }, // open floor
  'w' : { bg : 'wall', passable : false }, // wall
  's' : { bg : 'dirt', fg : 'source', passable : false }, // source
  'g' : { bg : 'goal', passable : true }, // goal
  'G' : { bg : 'goal_closed', passable : true }, // goal (closed)
  'h' : { bg : 'lava1', bg_alt : 'lava2', passable : true }, // hazard
  'c' : { bg : 'floor', fg : 'switch_on', passable : true }, // switch (on)
  'C' : { bg : 'floor', fg : 'switch_off', passable : true }, // switch (off)

  // Placeable tiles:
  'b' : { bg : 'floor', fg : 'barrier', passable : false }, // barrier
  'r' : { bg : 'floor', fg : 'rotator', passable : true }, // rotator
  't' : { bg : 'floor', fg : 'teleport_in', passable : true }, // teleporter (in)
  'T' : { bg : 'floor', fg : 'teleport_out', passable : true }, // teleporter (out)
  'S' : { bg : 'floor', fg : 'staircase', passable : true }, // staircase
};

function drawTile(c2d, x, y, tile) {
  var tile_def = tiles[tile];
  if (tile_def.bg_alt && (frame_time & 1)) {
    drawSprite(c2d, tile_def.bg_alt, x, y);
  } else {
    drawSprite(c2d, tile_def.bg, x, y);
  }
  if (tile_def.fg) {
    drawSprite(c2d, tile_def.fg, x, y);
  }
}

function drawTiles() {
  var canvas = document.getElementById("canvas");
  var c2d = canvas.getContext("2d");
  for (var y = 0; y < map_height; ++y) {
    for (var x = 0; x < map_width; ++x) {
      drawTile(c2d, x * tile_width, y * tile_height,
               map[y * map_width + x], true);
    }
  }
  if (hover_x >= 0 && hover_y >= 0 &&
      inventory[inventory_selected].count > 0 &&
      map[hover_y * map_width + hover_x] == ' ') {
    c2d.globalAlpha = 0.5;
    drawTile(c2d, hover_x * tile_width, hover_y * tile_height,
             inventory[inventory_selected].tile, true);
    c2d.globalAlpha = 1.0;
  }
}

function setTile(x, y, tile) {
  map = map.substr(0, y * map_width + x) + tile +
                   map.substr(y * map_width + x + 1);
}

function getTeleportCoordinates() {
    for (var y = 0; y < map_height; ++y) {
        for (var x = 0; x < map_width; ++x) {
	    if (getTileTypeAtCoords(x, y) == 'T') {
		return [x, y];
	    }
	}
    }

    return [-1, -1];
}

function getTileTypeAtCoords(x, y) {
    return map[y * map_width + x];
}

function outOfBounds(x, y) {
    if (x < 0 || x > map_width || y < 0 || y > map_height) {
	return true;
    }

    return false;
}
